package org.example.hashAndSet;

import java.util.Stack;

/**\
 * 回文串
 */
public class Code01_isPalindrome {
    public static class Node {
        public int value;
        public Node next;

        public Node(int value) {
            this.value = value;
        }
    }

    public static boolean isPalindrome1(Node head) {
        Stack<Node> stack = new Stack<>();
        Node cur = head;
        while (cur != null) {
            stack.add(cur);
            cur = cur.next;
        }
        while (head != null) {
            if(head.value != stack.pop().value) {
                return false;
            }
            head = head.next;
        }
        return true;
    }
    public static boolean isPalindrome2(Node head) {
         Stack<Node> stack = new Stack<>();
         Node slow = head;
         Node fast = head;
         while (fast != null && fast.next != null) {
             slow = slow.next;
             fast = fast.next.next;

         }
         while( slow != null) {
             stack.add(slow);
             slow = slow.next;
         }
         while (head != null && !stack.isEmpty()) {
             if(head.value != stack.pop().value) {
                 return false;
             }
             head = head.next;
         }
         return true;
    }
    public static boolean isPalindrome3(Node head) {
        if(head.next == null || head.next.next == null) {
            return true;
        }
        Node n1 = head;
        Node n2 = head;

        //找中点
        while(n2.next != null && n2.next.next != null) {
            n1 = n1.next;  //mid
            n2 = n2.next.next; // end
        }

        n2 = n1.next;
        n1.next = null;
        Node n3 = null;
        //  n1 -> n2 -> n3      变为   n1 <-- n2 -->n3 -> n4
        //   n1   n2    n3                   n1    n2    n3
        while (n2 != null) {
            n3 = n2.next;
            n2.next = n1;
            n1 = n2;
            n2 = n3;
        }
        // n1为最后一个节点
        n3 = n1; //保存最后一个节点  为后面恢复做准备
        n2 = head;
        boolean res = true;
        while (n1 != null && n2 != null) {
            if(n1.value != n2.value) {
                res = false;
                break;
            }
            n1 = n1.next;
            n2 = n2.next;

        }
        // 恢复
        n1 = n3.next;
        n3.next = null;
        while (n1 != null) {

            n2 = n1.next;
            n1.next = n3;
            n3 = n1;
            n1 = n2;
        }
        return res;

    }



    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(3);
        Node node3 = new Node(3);
        Node node4= new Node(1);
        //Node node5= new Node(1);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        //node4.next = node5;

        boolean palindrome1 = isPalindrome1(node1);
        //System.out.println(palindrome1);

        System.out.println(isPalindrome3(node1));
    }
}
